import { NextRequest } from 'next/server';
import { withMiddleware } from '@/lib/middleware/entry';
import { successResponse, errorResponse } from '@/lib/response';
import { prisma } from '@/lib/prisma';
import { authenticateRequest } from '@/utils/auth';

async function handler(req: NextRequest) {
  const authResult = await authenticateRequest(req);
  if (!authResult.success) {
    return errorResponse(authResult.error || '身份验证失败');
  }

  const { current = 1, pageSize = 10, name } = await req.json();
  const where: any = {};
  if (name) {
    where.name = {
      contains: name,
    };
  }

  const [total, agents] = await prisma.$transaction([
    prisma.agent.count({ where }),
    prisma.agent.findMany({
      where,
      skip: (current - 1) * pageSize,
      take: pageSize,
    }),
  ]);

  return successResponse({
    data: agents,
    total,
    pageSize,
    current,
  });
}

export const POST = withMiddleware(handler);